package com.neuedu.qian.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.qian.entity.Department;
import com.neuedu.qian.mapper.DepartmentMapper;
import com.neuedu.qian.service.IDepartmentService;
import com.neuedu.qian.vo.ResponseData;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service("departmentService")
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Override
    public List<Department> selectList(Department department) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        if(department==null){
            return getBaseMapper().selectList(queryWrapper);
        }
        String name=department.getName();
        if(name!=null){
            queryWrapper.like("name",name);
        }
        Integer userState=department.getUseState();
        if(userState!=null && 0!=userState){
            queryWrapper.eq("use_state",userState);
        }
        String code=department.getCode();
        if(code!=null){
            queryWrapper.like("code",code);
        }
        queryWrapper.orderByDesc("dep_id");
        return getBaseMapper().selectList(queryWrapper);
    }

    @Override
    public ResponseData insert(Department department) {
        if(department==null){
            return ResponseData.createFail("部门信息不能为空");
        }
        String name=department.getName();
        if(StrUtil.isEmpty(name)){
            return ResponseData.createFail("部门名称不能为空");
        }
        String code=department.getCode();
        if(StrUtil.isEmpty(code)){
            return ResponseData.createFail("部门编码不能为空");
        }
        QueryWrapper<Department> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("code",code);
        queryWrapper.or();
        queryWrapper.like("name",name);
        int count = getBaseMapper().selectCount(queryWrapper).intValue();
        if(count>0){
            return ResponseData.createFail("部门编码或名称已存在");
        }
        department.setUseState(1);
        department.setCreateTime(new Date());
        int rows=getBaseMapper().insert(department);
        return ResponseData.success(rows);
    }


    @Override
    public int update(Department department) {
        UpdateWrapper<Department> updateWrapper = new UpdateWrapper<>();
        department.setCreateTime(new Date());
        return getBaseMapper().updateById(department);
    }
}